package com.sp.shoppingplatform.controller;

import com.sp.shoppingplatform.common.result.Result;
import com.sp.shoppingplatform.entity.Product;
import com.sp.shoppingplatform.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/products", produces = MediaType.APPLICATION_JSON_VALUE)
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<Product> createProduct(@RequestBody Product product) {
        return Result.success(productService.createProduct(product));
    }

    @GetMapping("/{id}")
    public Result<Product> getProduct(@PathVariable Long id) {
        Product product = productService.getProductById(id);
        return product != null ? Result.success(product) : Result.error(404, "商品不存在");
    }

    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<Void> updateProduct(@RequestBody Product product) {
        boolean updated = productService.updateProduct(product);
        return updated ? Result.success() : Result.error(500, "更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteProduct(@PathVariable Long id) {
        boolean deleted = productService.deleteProduct(id);
        return deleted ? Result.success() : Result.error(500, "删除失败");
    }

    @GetMapping
    public Result<List<Product>> getProductList() {
        return Result.success(productService.getProductList());
    }

    @GetMapping("/category/{category}")
    public Result<List<Product>> getProductsByCategory(@PathVariable String category) {
        return Result.success(productService.getProductsByCategory(category));
    }
}
